import os
import sys
import shutil
import webbrowser
from datetime import datetime
from PyQt6.QtWidgets import (QMainWindow, QVBoxLayout, QHBoxLayout, QToolButton,
                            QPushButton, QLabel, QProgressBar, QTextEdit,
                            QFileDialog, QWidget, QMessageBox, QSizePolicy)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize
from PyQt6.QtGui import QPixmap, QIcon, QFont, QColor, QPalette

# Add parent directory to path to allow absolute imports
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from ui.drop_area import DropArea
from core.converter import PDFConverter

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('PDF to HTML Converter')
        self.setMinimumSize(800, 800)
        
        self.pdf_path = ''
        self.output_dir = os.path.expanduser('~/Documents/PDF_Exports')
        self.converter = None
        self.is_dark = False
        self.last_output_dir = ''
        
        # Create output directory if it doesn't exist
        os.makedirs(self.output_dir, exist_ok=True)
        
        self.init_ui()
        self.apply_theme()
        
    def init_ui(self):
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout(main_widget)
        
        # Title and theme toggle
        title_layout = QHBoxLayout()
        title = QLabel('PDF to HTML Converter')
        title.setStyleSheet('font-size: 24px; font-weight: bold; margin: 10px;')
        title.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        
        self.theme_btn = QToolButton()
        self.theme_btn.setCheckable(True)
        self.theme_btn.setChecked(self.is_dark)
        self.theme_btn.setToolTip('Toggle Dark/Light Mode')
        self.theme_btn.setIconSize(QSize(24, 24))
        self.theme_btn.clicked.connect(self.toggle_theme)
        
        title_layout.addWidget(title, 1)
        title_layout.addWidget(self.theme_btn)
        layout.addLayout(title_layout)
        
        # Drop area
        self.drop_area = DropArea(self)
        self.drop_area.mousePressEvent = self.browse_pdf
        layout.addWidget(self.drop_area)
        
        # Selected file label
        self.file_label = QLabel('No file selected')
        self.file_label.setWordWrap(True)
        self.file_label.setStyleSheet('color: #666; margin: 5px 0;')
        layout.addWidget(self.file_label)
        
        # Progress bar
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setFormat('Ready')
        self.progress_bar.setStyleSheet('height: 25px; margin: 10px 0;')
        layout.addWidget(self.progress_bar)
        
        # Buttons
        button_layout = QHBoxLayout()
        self.browse_btn = QPushButton('Browse PDF')
        self.browse_btn.clicked.connect(self.browse_pdf)
        
        self.convert_btn = QPushButton('Convert to HTML')
        self.convert_btn.clicked.connect(self.start_conversion)
        self.convert_btn.setEnabled(False)
        
        button_layout.addWidget(self.browse_btn)
        button_layout.addStretch()
        button_layout.addWidget(self.convert_btn)
        layout.addLayout(button_layout)
        
        # Log area
        log_label = QLabel('Conversion Log:')
        log_label.setStyleSheet('font-weight: bold; margin-top: 10px;')
        layout.addWidget(log_label)
        
        self.log_area = QTextEdit()
        self.log_area.setReadOnly(True)
        self.log_area.setFontFamily('Consolas' if sys.platform == 'win32' else 'Monospace')
        layout.addWidget(self.log_area, 1)
        
        # Status bar
        self.status_bar = self.statusBar()
        self.status_bar.showMessage('Ready')
    
    def apply_theme(self):
        """Apply the current theme based on is_dark setting"""
        self.update_theme()
        self.update_drop_area_style()
    
    def toggle_theme(self):
        """Toggle between dark and light theme"""
        self.is_dark = not self.is_dark
        self.apply_theme()
    
    def update_theme(self):
        """Update the application theme based on current theme state"""
        if self.is_dark:
            # Dark theme
            self.setStyleSheet('''
                QMainWindow, QDialog {
                    background-color: #2b2b2b;
                    color: #e0e0e0;
                }
                QLabel {
                    color: #e0e0e0;
                }
                QTextEdit, QPlainTextEdit {
                    background-color: #3c3f41;
                    color: #e0e0e0;
                    border: 1px solid #555555;
                }
                QPushButton {
                    background-color: #2e7d32;
                    color: #ffffff;
                    border: none;
                    padding: 8px 16px;
                    border-radius: 4px;
                }
                QPushButton:disabled {
                    background-color: #555555;
                    color: #888888;
                }
                QPushButton:hover:!disabled {
                    background-color: #1b5e20;
                }
                QProgressBar {
                    border: 1px solid #555555;
                    border-radius: 4px;
                    text-align: center;
                    background: #3c3f41;
                    color: #e0e0e0;
                }
                QProgressBar::chunk {
                    background-color: #2e7d32;
                    width: 10px;
                }
                QScrollBar:vertical {
                    border: 1px solid #555555;
                    background: #3c3f41;
                    width: 15px;
                    margin: 15px 0 15px 0;
                }
                QScrollBar::handle:vertical {
                    background: #555555;
                    min-height: 20px;
                }
                QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                    border: 1px solid #555555;
                    background: #3c3f41;
                    height: 15px;
                }
                QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                    background: none;
                }
            ''')
            # Set dark theme icon (moon icon)
            self.theme_btn.setIcon(QIcon.fromTheme("weather-clear-night"))
        else:
            # Light theme
            self.setStyleSheet('''
                QMainWindow, QDialog {
                    background-color: #f5f5f5;
                    color: #333333;
                }
                QLabel {
                    color: #333333;
                }
                QTextEdit, QPlainTextEdit {
                    background-color: #ffffff;
                    color: #333333;
                    border: 1px solid #cccccc;
                }
                QPushButton {
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    padding: 8px 16px;
                    border-radius: 4px;
                }
                QPushButton:disabled {
                    background-color: #cccccc;
                }
                QPushButton:hover:!disabled {
                    background-color: #45a049;
                }
                QProgressBar {
                    border: 1px solid #cccccc;
                    border-radius: 4px;
                    text-align: center;
                    background: #ffffff;
                }
                QProgressBar::chunk {
                    background-color: #4CAF50;
                    width: 10px;
                }
                QScrollBar:vertical {
                    border: 1px solid #cccccc;
                    background: #f0f0f0;
                    width: 15px;
                    margin: 15px 0 15px 0;
                }
                QScrollBar::handle:vertical {
                    background: #c0c0c0;
                    min-height: 20px;
                }
                QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                    border: 1px solid #cccccc;
                    background: #f0f0f0;
                    height: 15px;
                }
            ''')
            # Set light theme icon (sun icon)
            self.theme_btn.setIcon(QIcon.fromTheme("weather-clear"))
        
        self.update_drop_area_style()
    
    def update_drop_area_style(self):
        """Update the drop area style based on current theme"""
        if self.is_dark:
            self.drop_area.setStyleSheet('''
                QLabel {
                    border: 2px dashed #666666;
                    border-radius: 10px;
                    padding: 40px;
                    background-color: #3c3f41;
                    color: #aaaaaa;
                    font-size: 16px;
                    margin: 10px 0;
                }
                QLabel:hover {
                    border-color: #4CAF50;
                    background-color: #45494a;
                }
            ''')
        else:
            self.drop_area.setStyleSheet('''
                QLabel {
                    border: 2px dashed #aaaaaa;
                    border-radius: 10px;
                    padding: 40px;
                    background-color: #f9f9f9;
                    color: #666666;
                    font-size: 16px;
                    margin: 10px 0;
                }
                QLabel:hover {
                    border-color: #4CAF50;
                    background-color: #f0f8f0;
                }
            ''')
    
    def browse_pdf(self, event=None):
        """Open file dialog to select a PDF file"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, 'Select PDF File', '', 'PDF Files (*.pdf);;All Files (*)')
        if file_path:
            self.set_pdf_path(file_path)
    
    def set_pdf_path(self, file_path):
        """Set the PDF file path and update UI accordingly"""
        if not file_path:
            return
            
        self.pdf_path = file_path
        self.file_label.setText(f'Selected: {os.path.basename(file_path)}')
        self.convert_btn.setEnabled(True)
        self.status_bar.showMessage(f'Ready to convert: {os.path.basename(file_path)}')
        self.log(f'Loaded PDF: {file_path}')
        self.log(f'Selected file: {file_path}')
    
    def start_conversion(self):
        """Start the PDF to HTML conversion process"""
        if not self.pdf_path:
            QMessageBox.warning(self, 'Error', 'Please select a PDF file first.')
            return
            
        # Disable controls during conversion
        self.set_controls_enabled(False)
        self.progress_bar.setValue(0)
        self.progress_bar.setFormat('Starting conversion...')
        self.log('Starting conversion process...')
        
        # Create and start converter thread
        self.converter = PDFConverter(self.pdf_path, self.output_dir)
        self.converter.progress_updated.connect(self.update_progress)
        self.converter.conversion_finished.connect(self.conversion_complete)
        self.converter.error_occurred.connect(self.conversion_error)
        self.converter.finished.connect(self.converter.deleteLater)
        self.converter.start()
        
        # Update UI
        self.status_bar.showMessage('Converting PDF to HTML...')
    
    def update_progress(self, value, message):
        """Update progress bar and log message"""
        self.progress_bar.setValue(value)
        self.progress_bar.setFormat(f'{message} ({value}%)')
        self.log(message)
        
        # Update status bar for important messages
        if value >= 90 or 'error' in message.lower():
            self.status_bar.showMessage(message)
    
    def conversion_complete(self, html_path, output_dir):
        """Handle successful conversion completion"""
        self.last_output_dir = output_dir
        self.set_controls_enabled(True)
        
        # Show success message
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Icon.Information)
        msg.setWindowTitle('Conversion Complete')
        msg.setText('PDF conversion completed successfully!')
        msg.setInformativeText(f'HTML file saved to:\n{html_path}')
        
        # Add buttons
        open_btn = msg.addButton('Open in Browser', QMessageBox.ButtonRole.ActionRole)
        open_folder_btn = msg.addButton('Open Output Folder', QMessageBox.ButtonRole.ActionRole)
        msg.addButton(QMessageBox.StandardButton.Ok)
        
        # Show the message box
        msg.exec()
        
        # Handle button clicks
        if msg.clickedButton() == open_btn:
            webbrowser.open(f'file://{html_path}')
        elif msg.clickedButton() == open_folder_btn:
            os.startfile(os.path.dirname(html_path))
    
    def conversion_error(self, error_message):
        """Handle conversion errors"""
        self.set_controls_enabled(True)
        self.log(f'Error: {error_message}')
        self.status_bar.showMessage('Conversion failed')
        
        # Show error message
        QMessageBox.critical(
            self,
            'Conversion Error',
            f'An error occurred during conversion:\n{error_message}'
        )
    
    def set_controls_enabled(self, enabled):
        """Enable or disable UI controls"""
        self.browse_btn.setEnabled(enabled)
        self.convert_btn.setEnabled(enabled and bool(self.pdf_path))
        self.drop_area.setEnabled(enabled)
        
        # Update button text based on state
        if enabled:
            self.convert_btn.setText('Convert to HTML')
        else:
            self.convert_btn.setText('Converting...')
    
    def log(self, message):
        """Add a message to the log with timestamp"""
        timestamp = datetime.now().strftime('%H:%M:%S')
        self.log_area.append(f'[{timestamp}] {message}')
        self.log_area.verticalScrollBar().setValue(
            self.log_area.verticalScrollBar().maximum()
        )
    
    def closeEvent(self, event):
        """Handle application close event"""
        # Stop any running conversion
        try:
            if hasattr(self, 'converter') and self.converter is not None:
                try:
                    if (hasattr(self.converter, 'isRunning') and 
                        callable(self.converter.isRunning) and 
                        self.converter.isRunning()):
                        
                        self.log('Stopping conversion...')
                        if hasattr(self.converter, 'stop') and callable(self.converter.stop):
                            self.converter.stop()
                        if hasattr(self.converter, 'wait') and callable(self.converter.wait):
                            self.converter.wait(1000)  # Wait up to 1 second
                except RuntimeError as e:
                    # Ignore errors about C++ object being deleted
                    if 'wrapped C/C++ object' not in str(e):
                        print(f'Error stopping converter: {e}', file=sys.stderr)
        except Exception as e:
            print(f'Error in closeEvent: {e}', file=sys.stderr)

        # Clean up temporary directories
        try:
            if hasattr(self, 'last_output_dir') and self.last_output_dir:
                if os.path.exists(self.last_output_dir):
                    shutil.rmtree(self.last_output_dir, ignore_errors=True)
        except Exception as e:
            print(f'Error cleaning up: {e}', file=sys.stderr)

        # Ensure the application exits cleanly
        event.accept()
        super().closeEvent(event)